package com.itheima.reggie.controller;

import com.itheima.reggie.common.Result;
import com.itheima.reggie.common.exception.BusinessException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

/**
 * @author Yan
 * @date 2022/2/26
 * 文件上传和下载
 */
@RestController
@RequestMapping("/common")
@Slf4j
public class CommonController {
    @Value("${reggie.path}")
    private String basePath;


    @PostMapping("upload")
    public Result<String> upload(MultipartFile file){

        //原始文件名
        String originalFilename = file.getOriginalFilename();

        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

        //使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() +suffix;

        //创建一个目录对象
        File dir =new File(basePath);


        //判断当前目录是否存在
        if (!dir.exists()){
            //目录不存在，需要创建
            boolean mkdirs = dir.mkdirs();
        }

        //将制定文件转存到指定位置
        try {
            file.transferTo(new File(basePath + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return Result.success(fileName);

    }

    /**
     * 文件下载
     * @param name
     * @param response
     */
    @GetMapping("download")
    public void download(String name, HttpServletResponse response){
        try {
            //输入流，通过输入流读取文件内容
            FileInputStream fileInputStream =new FileInputStream(basePath+name);
            //使用输入流将文件写回浏览器
            ServletOutputStream outputStream =response.getOutputStream();

            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes))!=-1){
                outputStream.write(bytes,0,len);
                outputStream.flush();
            }
            //关闭资源
            outputStream.close();
            fileInputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void download2(String name,HttpServletResponse response) throws IOException {
        ServletOutputStream outputStream = response.getOutputStream();

        //1. 创建文件
        File file =new File("D:\\"+name);
        //2. 文件转成字节输入流
        FileInputStream fileInputStream =new FileInputStream(file);

        //告诉浏览器以图片格式解析
        response.setContentType("image/jpeg");

        int len = 0;
        byte[] bytes = new byte[1024];
        while ((len = fileInputStream.read(bytes))!=-1){
            //向浏览器输出字节
            outputStream.write(bytes,0,len);
            outputStream.flush();
        }

        //使用工具类commons-io
        //FileUtils.copyFile();
        //1.文件转字节
        byte[] bytes1 = FileUtils.readFileToByteArray(file);
        //2.字节转文件
        FileUtils.writeByteArrayToFile(file,bytes);
        //3.流转成字节
        //IOUtils.readFully();
        //4.字节转成流
        //IOUtils.write();

        //关闭资源
        outputStream.close();
        fileInputStream.close();

    }

    //@PostMapping("upload2")
    public Result<String> upload2(MultipartFile file){
        /*//将前端传递的文件转成字节，输入流，resource
        byte[] bytes = file.getBytes();
        InputStream inputStream = file.getInputStream();
        Resource resource = file.getResource();

        //上传文件的类型
        String contentType = file.getContentType();

        //文件大小（字节）
        long size = file.getSize();

        //文件名称 html里file的名，file
        String name = file.getName();

        //判断文件是否为空
        boolean empty = file.isEmpty();*/



        //1.获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        //2. 获取文件后缀名
        String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
        //3.生成一个不重复文件名称
        String newFileName = UUID.randomUUID().toString();
        //4.构造一个带后缀名文件名
        StringBuilder stringBuilder =new StringBuilder();
        String newFileNameWithSuffix = stringBuilder.append(newFileName).append(suffix).toString();
        //5.文件存贮（D:\）
        String filePath = new StringBuilder().append(basePath).append(newFileNameWithSuffix).toString();

        File newFile = new File(filePath);
        //6.判断文件是否存在
        if (!newFile.exists()){
            newFile.mkdirs();
        }
        //7.数据存储
        try {
            file.transferTo(newFile);
        } catch (IOException e) {
            e.printStackTrace();
            throw new BusinessException("上传图片失败");
        }
        return Result.success(newFileNameWithSuffix);
    }

}
